package org.microservice.system.utils;

import com.baomidou.mybatisplus.generator.AutoGenerator;
import com.baomidou.mybatisplus.generator.InjectionConfig;
import com.baomidou.mybatisplus.generator.config.*;
import com.baomidou.mybatisplus.generator.config.converts.MySqlTypeConvert;
import com.baomidou.mybatisplus.generator.config.po.TableInfo;
import com.baomidou.mybatisplus.generator.config.rules.DbColumnType;
import com.baomidou.mybatisplus.generator.config.rules.DbType;
import com.baomidou.mybatisplus.generator.config.rules.NamingStrategy;
import lombok.extern.slf4j.Slf4j;
import org.microservice.common.util.AuthUtil;
import org.microservice.common.util.ZipUtil;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.stereotype.Component;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created with IntelliJ IDEA.
 * User: 齐丹枫
 * Date: 2018/7/26
 * Time: 9:45
 * To change this template use File | Settings | File Templates.
 * Description:
 */
@RefreshScope
@Component
@Slf4j
public class GenerateCodeUtil {

    @Value("${generate.jdbc.driverName}")
    private String driverName;

    @Value("${generate.jdbc.userName}")
    private String userName;

    @Value("${generate.jdbc.password}")
    private String password;

    @Value("${generate.jdbc.url}")
    private String url;


    public byte[] generate(String packageName, String moduleName, String[] tableNames) throws Exception{

        AutoGenerator mpg = new AutoGenerator();

        GlobalConfig gc = new GlobalConfig();

        gc.setOutputDir("."+File.separator);
        gc.setFileOverride(true);
        gc.setActiveRecord(false);// 不需要ActiveRecord特性的请改为false
        gc.setEnableCache(false);// XML 二级缓存
        gc.setBaseResultMap(true);// XML ResultMap
        gc.setBaseColumnList(false);// XML columList
        // .setKotlin(true) 是否生成 kotlin 代码
        gc.setAuthor(AuthUtil.getUserName());

        // 自定义文件命名，注意 %s 会自动填充表实体属性！
        gc.setMapperName("%sDao");
        gc.setXmlName("%sDao");

        gc.setServiceName("%sService");
        gc.setServiceImplName("%sServiceImpl");
        gc.setControllerName("%sController");
        mpg.setGlobalConfig(gc);
        // 数据源配置
        DataSourceConfig dsc = new DataSourceConfig();
        dsc.setDbType(DbType.MYSQL);
        dsc.setTypeConvert(new MySqlTypeConvert() {
            // 自定义数据库表字段类型转换【可选】
            @Override
            public DbColumnType processTypeConvert(String fieldType) {
                return super.processTypeConvert(fieldType);
            }
        });
        dsc.setDriverName(driverName);
        dsc.setUsername(userName);
        dsc.setPassword(password);
        dsc.setUrl(url);
        mpg.setDataSource(dsc);

        StrategyConfig strategy = new StrategyConfig();

        strategy.setNaming(NamingStrategy.underline_to_camel);// 表名生成策略
        strategy.setInclude(tableNames); // 需要生成的表

        // 自定义实体父类
        strategy.setSuperEntityClass("org.microservice.common.base.AbstractAuditingEntity");
        strategy.setSuperControllerClass("org.microservice.common.base.BaseControllerImpl");
        strategy.setEntityLombokModel(true);
        mpg.setStrategy(strategy);
        // 包配置
        PackageConfig pc = new PackageConfig();
        pc.setParent(packageName);
        pc.setModuleName(moduleName);
        mpg.setPackageInfo(pc);
        String separator =File.separator;
        String[] split = packageName.split("\\.");

        String sourcePath = "."+separator+split[0];

        String path = "." + separator + packageName.replace(".", separator) + separator + moduleName;
        // 注入自定义配置，可以在 VM 中使用 cfg.abc 【可无】
        InjectionConfig cfg = new InjectionConfig() {
            @Override
            public void initMap() {
                Map<String, Object> map = new HashMap<String, Object>();
                map.put("abc", this.getConfig().getGlobalConfig().getAuthor() + "-mp");
                this.setMap(map);
            }
        };

        // 自定义 xxList.vue 生成
        List<FileOutConfig> focList = new ArrayList<FileOutConfig>();
        focList.add(new FileOutConfig("/templates/index.vue.vm") {
            @Override
            public String outputFile(TableInfo tableInfo) {
                // 自定义输入文件名称
                String p = path + separator + "vue" + separator + tableInfo.getEntityName() + separator + "index.vue";
                File file = new File(p);
                if (!file.getParentFile().exists()) {
                    try {
                        file.getParentFile().mkdirs();
                        file.createNewFile();
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
                return p;
            }
        });

        focList.add(new FileOutConfig("/templates/index.js.vm") {
            @Override
            public String outputFile(TableInfo tableInfo) {
                // 自定义输入文件名称
                String p = path + separator + "vue" + separator + tableInfo.getEntityName() + separator + "index.js";
                File file = new File(p);
                if (!file.getParentFile().exists()) {
                    try {
                        file.getParentFile().mkdirs();
                        file.createNewFile();
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
                return p;
            }
        });

        focList.add(new FileOutConfig("/templates/addOrUpdate.vue.vm") {
            @Override
            public String outputFile(TableInfo tableInfo) {
                // 自定义输入文件名称
                String p = path + separator + "vue" + separator + tableInfo.getEntityName() + separator + "addOrUpdate.vue";
                File file = new File(p);
                if (!file.getParentFile().exists()) {
                    try {
                        file.getParentFile().mkdirs();
                        file.createNewFile();
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
                return p;
            }
        });




        cfg.setFileOutConfigList(focList);
        mpg.setCfg(cfg);
        // 执行生成
        mpg.execute();
        byte[] bytes = ZipUtil.createZip(sourcePath);

        File file = new File(sourcePath);
        deleteFile(file);
        return bytes;
    }

    /**
     * 先根遍历序递归删除文件夹
     *
     * @param dirFile 要被删除的文件或者目录
     * @return 删除成功返回true, 否则返回false
     */
    public boolean deleteFile(File dirFile) {
        // 如果dir对应的文件不存在，则退出
        if (!dirFile.exists()) {
            return false;
        }

        if (dirFile.isFile()) {
            return dirFile.delete();
        } else {

            for (File file : dirFile.listFiles()) {
                deleteFile(file);
            }
        }

        return dirFile.delete();
    }


}
